<!-- 功能：导入导出配置弹窗 | 作者：menghao.yan | 邮箱：yxs2615@163.com | 时间：2023年08月24日 14:23:00 -->
<template>
  <!-- 弹出框 -->
  <a-modal v-model:open="visible" title="导入导出配置" width="500px" class="y-modal" okText="创建" @ok="onSubmit" @cancel="onCancel">
    <a-form :label-col="{ span:6 }" :wrapper-col="{span: 14}">
      <a-form-item label="所属控制器" v-bind="validateInfos.controller">
        <a-select v-model:value="modelRef.controller" placeholder="请选择所属控制器">
          <a-select-option :value="index" v-for="item, index in controllerData">{{item.name}}</a-select-option>
        </a-select>
      </a-form-item>
      <a-row>
        <a-col :offset="6">
          <a-button type="link" class="y-btn" @click="daoRuPeiZhi">
            <template #icon>
              <PoweroffOutlined />
            </template>
            导入配置
          </a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-alert banner message="警告: 该操作会将现有配置全部清除，并导入以前保存的配置（不包括磁盘信息），请慎重操作！" type="error" show-icon>
            <template #icon>
              <WarningOutlined />
            </template>
          </a-alert>
        </a-col>
      </a-row>
      <a-row>
        <a-col :offset="6">
          <a-button type="link" class="y-btn" @click="daoChuPeiZhi">
            <template #icon>
              <DeliveredProcedureOutlined />
            </template>
            导出配置
          </a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-alert banner message="说明: 该操作将导出当前NAS的基本配置信息，请保存到适当的位置！" type="warning" show-icon></a-alert>
        </a-col>
      </a-row>
      <a-row>
        <a-col :offset="6">
          <a-button type="link" class="y-btn" @click="daoChuCiPanPeiZhi">
            <template #icon>
              <DeliveredProcedureOutlined />
            </template>
            导出磁盘信息
          </a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-alert banner message="说明: 该操作将导出当前所有磁盘的信息，请保存到适当的位置！" type="warning" show-icon></a-alert>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>

  <a-modal v-model:open="daoRuVisible" title="导入配置" width="200px" class="y-modal" okText="创建" @ok="onDaoRu">
    <a-upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove">
      <a-button>
        <upload-outlined></upload-outlined>
        选择文件
      </a-button>
    </a-upload>
  </a-modal>

  <a-modal v-model:open="daoChuPeiZhiVisible" title="导出配置" width="400px" class="y-modal" :footer="null">
    <a-row>
      <a-col :span="24">
        <a-alert banner message="配置文件打包成功，点击下面的链接保存文件，请妥善保管！" type="error" show-icon>
          <template #icon>
            <WarningOutlined />
          </template>
        </a-alert>
      </a-col>
    </a-row>
    <a-button v-if="daoChuPeiZhiPack" @click="daoChuPeiZhiFile">
      {{ daoChuPeiZhiPack.packname || '暂无'}}
    </a-button>
  </a-modal>
  <a-modal v-model:open="daoChuCiPanVisible" title="导出配置" width="400px" class="y-modal" :footer="null">
    <a-row>
      <a-col :span="24">
        <a-alert banner message="配置文件打包成功，点击下面的链接保存文件，请妥善保管！" type="error" show-icon>
          <template #icon>
            <WarningOutlined />
          </template>
        </a-alert>
      </a-col>
    </a-row>
    <a-button v-if="daoChuCiPanPack" @click="daoChuCiPanFile">
      {{ daoChuCiPanPack.diskinfofile || '暂无'}}
    </a-button>
  </a-modal>
</template>

<script setup>
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { downloadFile } from '@/utils/fileDownload'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const { visible } = toRefs(props)

// 定义组件的事件
const emits = defineEmits(['update:visible'])

import { Form } from 'ant-design-vue'

const useForm = Form.useForm

const modelRef = reactive({
  controller: ''
})

const rulesRef = reactive({
  controller: [
    {
      required: true,
      message: '请输入所属控制器'
    }
  ]
})

const { resetFields, validate, validateInfos, mergeValidateInfo } = useForm(modelRef, rulesRef)
const onSubmit = () => {
  validate()
    .then(() => {
      console.log('导入导出配置>>', toRaw(modelRef))
      onCancel()
    })
    .catch(err => {
      console.log('error', err)
    })
}

const onCancel = () => {
  // 触发自定义事件来通知父组件关闭弹窗
  emits('update:visible', false)
}

// 控制器的数据
let controllerData = ref([])
// 获取控制器
const initController = () => {
  controllerData.value = []
  apiWs.controller().subscribe(resp => {
    if (resp && resp.length > 0) {
      for (let i = 0; i < resp.length; i++) {
        let controllerName = resp[i]
        controllerData.value[i] = {
          name: controllerName
        }
      }
    }
  })
}

onMounted(() => {
  initController() // 加载控制器的接口
})

const daoRuVisible = ref(false)
// 导入配置
const daoRuPeiZhi = () => {
  Modal.confirm({
    title: '确认操作',
    icon: h(ExclamationCircleOutlined),
    content: '您确认要导入配置文件，并将系统当前配置文件替换吗?',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      console.log('OK')
      daoRuVisible.value = true
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const fileList = ref([])

const beforeUpload = file => {
  fileList.value = [file]
  return false
}

function fileToBlob(file) {
  // 创建 FileReader 对象
  let reader = new FileReader()
  return new Promise(resolve => {
    // FileReader 添加 load 事件
    reader.addEventListener('load', e => {
      let blob
      if (typeof e.target.result === 'object') {
        blob = new Blob([e.target.result])
      } else {
        blob = e.target.result
      }
      console.log(Object.prototype.toString.call(blob))
      resolve(blob)
    })
    // FileReader 以 ArrayBuffer 格式 读取 File 对象中数据
    reader.readAsArrayBuffer(file)
  })
}

let onDaoRu = () => {
  //   fileToBlob(fileList.value[0]).then(fileBlob => {
  //     let params = {
  //       qqfile: fileBlob,
  //       cid: modelRef.controller
  //     }
  //     apiWs.systemtoolImportconf(params).subscribe(resp => {
  //       console.log(resp)
  //     })
  //   })

  let params = {
    qqfile: fileList.value[0],
    cid: modelRef.controller
  }
  apiWs.systemtoolImportconf(params).subscribe(resp => {
    console.log(resp)
  })
}

const daoChuCiPanVisible = ref(false)
const daoChuCiPanPack = ref({})

// 导出磁盘配置
let daoChuCiPanPeiZhi = () => {
  let params = {
    cid: modelRef.controller
  }
  apiWs.systemtoolExportdiskinfoget(params).subscribe(resp => {
    daoChuCiPanVisible.value = true
    daoChuCiPanPack.value = resp
  })
}

// 导出磁盘文件
let daoChuCiPanFile = () => {
  let params = {
    cid: modelRef.controller
  }
  apiWs.systemtoolExportdiskinfo(params).subscribe(resp => {
    downloadFile(resp, daoChuCiPanPack.value.diskinfofile)
  })
}

const daoChuPeiZhiVisible = ref(false)
const daoChuPeiZhiPack = ref({})
// 导出配置
let daoChuPeiZhi = () => {
  let params = {
    cid: modelRef.controller
  }
  apiWs.systemtoolExportconfget(params).subscribe(resp => {
    daoChuPeiZhiVisible.value = true
    daoChuPeiZhiPack.value = resp
  })
}

// 导出配置文件
let daoChuPeiZhiFile = () => {
  let params = {
    cid: modelRef.controller
  }
  apiWs.systemtoolExportconf(params).subscribe(resp => {
    downloadFile(resp, daoChuPeiZhiPack.value.packname)
  })
}
</script>


<style scoped>
.ant-row {
  margin-bottom: 10px;
}
</style>